package cn.stylefeng.guns.modular.file.controller;

import cn.hutool.json.JSON;
import cn.stylefeng.guns.modular.file.entity.FileJson;
import cn.stylefeng.guns.sys.modular.system.entity.FileInfo;
import cn.stylefeng.guns.sys.modular.system.service.FileInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    FileInfoService fileInfoService;

    @RequestMapping("/get")
    public FileJson getone(String id) {
        FileJson json=new FileJson();
        if(id == null|| id==""){
            json.setResponse(false);
            return json;
        }
        QueryWrapper<FileInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("file_id",id);
        FileInfo info = fileInfoService.getOne(queryWrapper);
        String File = info.getFilePath();
        String fileSuffix=info.getFileSuffix();
        String datatype=null;

        if(fileSuffix.equals("png")){
            datatype="data:image/png;base64,";
        }else if(fileSuffix.equals("jpeg")){
            datatype="data:image/jpeg;base64,";
        }

        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(File);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        json.setResponse(true);
        json.setData(datatype+encoder.encode(data));
        return json;
    }
}
